var comPort = chrome.extension.connect({name:'jettube'});
comPort.onMessage.addListener(function (msg) {
    updateDD(msg);
});


function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(document.URL);
    if (results == null) return "";
    else return results[1];
}

var videoID;
var title;

$(document).ready(function() {
    videoID = gup('v');
    title = document.title.substring(10);
    createDOMdump();
    addJetTubeClicker(title);
});

function createDOMdump()
{
    var domDump = document.createElement('div');
    domDump.setAttribute('id','domDump');
    domDump.hidden = true;
    domDump.addEventListener('jetClick',function() {
	var stationKey = document.getElementById('domDump').innerText;
	chrome.extension.sendRequest({videoID:videoID, videoTitle:title,stationKey:stationKey},function(response) {
  addSongResponse(response);
  });
  });
    document.body.appendChild(domDump);
}

function addJetTubeClicker(videoTitle)
{
  chrome.extension.sendRequest({messageType: 'createDD'},function(response) {
  createDD(response);
  });
}

function createAddButton()
{
  var menuBar = document.getElementById('watch-headline-user-info');

    spanHTML = '<span class="subscription-container">';
    //spanHTML = '<span data-subscription-type="user" data-subscription-xsrf="pmwFJv04pxXqSOhVczEtjQwZSw58MA==" data-subscription-expandable-id="subscription-button-module-menu" data-subscription-username="SnoopDoggVEVO" data-subscription-menu-type="expander" class="subscription-container">';
    spanHTML += '<button type="button" class="subscribe-button yt-uix-button yt-uix-tooltip" onclick="document.getElementById(\'jetTubeDiv\').removeAttribute(\'hidden\')" title="Click to add ' + title + ' to JetTube!" role="button" aria-pressed="false" data-tooltip="Click to add ' + title + ' to JetTube!" data-tooltip-title="Click to add ' + title + ' to JetTube!" data-tooltip-timer="11048" data-content-id="yt-uix-tooltip1-content"><span class="yt-uix-button-content">Add To JetTube!</span></button>';
    spanHTML+= "</span>";
    menuBar.innerHTML+=spanHTML;
    
    var theParent = menuBar;
    var theKids = theParent.children;
    var num = theKids.length - 1;
    theParent.insertBefore(theKids[num], theParent.firstChild);
}

function createDD(response)
{
  createAddButton();
  addDDBox();
  document.getElementById('jetTitle').innerText = 'Add ' + title + ' to a station';
  name = response.name;
  if (name == 'null') {
    createDDWOUser(response);
    return;
  }
  createDDWUser(response);
}

function addDDBox()
{
  var watch = document.getElementById('watch-headline');
    
    
    
    var watchText = '<div id="jetTubeDiv" class="subscription-menu-expandable subscription-menu" hidden>\
      <span class="subscription-menu-loader hid" style="display: none; ">Loading...</span>\
      <div class="subscription-menu-body" style=""><button class="close master-sprite" onclick="document.getElementById(\'jetTubeDiv\').hidden = true"; return false;" type="button">close</button>\
  <form class="subscription-menu-form" id="jetTubeForm">\
  <div id="jetStations" >\
  <h1 id="jetTitle"></h1>\
      <h1>Stations</h1>\
      <ul id="stationList">\
      </ul>\
      </div>\
      <div id="jetUser">\
      </div>\
      <div  id="jetTubeStatus"></div>\
  </form></div>\
  </div>';

  
  watch.innerHTML+=watchText;
}

function createDDWUser(response)
{
  appendPublicStations(response);
  appendPrivateStations(response);
  
  pic = document.createElement('img');
  pic.src = response.picUrl;
  nameDiv = document.createElement('div');
  nameDiv.innerHTML = '<h3>' + response.name + '</h3>';
  
  document.getElementById('jetUser').appendChild(nameDiv);
  document.getElementById('jetUser').appendChild(pic);
  
  
  
  
}

function createDDWOUser(response)
{
  appendPublicStations(response);
  
  document.getElementById('jetUser').innerText = "Login with the JetTube Icon on the menu bar to get private stations and show others what songs you have added.";
}

function appendStations(ps)
{
  ns = ps.length;
  sl = document.getElementById('stationList');
  for (var i = 0; i < ns; i++)
  {
    newS = ps[i];
    newLI = document.createElement('li');
    newLI.setAttribute('name',newS.station_key);
    newLI.setAttribute('onclick',onclick='document.getElementById(\'domDump\').innerText = this.getAttribute(\'name\');var customEvent = document.createEvent(\'Event\');customEvent.initEvent(\'jetClick\', true, true);document.getElementById(\'domDump\').dispatchEvent(customEvent);');
    newLI.style.cursor = 'pointer';
    newLI.innerText = newS.station_name;
    sl.appendChild(newLI);
  }
}

function appendPublicStations(response)
{
  ps = response.pubStations;
  appendStations(ps);
}

function appendPrivateStations(response)
{
  ps = response.privStations;
  appendStations(ps);
}



function addSongResponse(data)
{
  statusDiv = document.getElementById('jetTubeStatus');
  messageType = data.messageType;
  if (!(messageType == 'addSong')) return;
  status = data.status;
  station = data.station;
  var responseString;
    var fail = true;
    if (status == 'NO_EMBED') responseString = title + ' cannot be added to JetTube! This video does not allow embedding.';
    else if (status == 'TOO_RECENT') responseString = title + ' cannot be added to JetTube! This video was already added recently on ' + station + '.';
    else if (status == 'OK') {
        responseString = title + " added to " + station + " Station on The JetTube!";
        fail = false;
    }
    else
    {
    responseString = title + ' cannot be added to JetTube! There was a server error.';
    }
    var colorchoice;
    if (fail) {
        colorchoice = '#bbb';
    }
    else {
        colorchoice = '#36b';
    }
    // Create the overlay at the top of the page and fill it with data.
    
    statusDiv.innerText = responseString;
    statusDiv.style.background = colorchoice;
    statusDiv.style.color = '#fff';
    statusDiv.style.padding = '10px';
    statusDiv.style.position = 'relative';
    statusDiv.style.zIndex = '123456';
    statusDiv.style.font = '14px Arial';
}


chrome.extension.onRequest.addListener(addSongResponse);




